package com.gqz.defect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gqz.common.core.domain.RequestForm;
import com.gqz.common.core.utils.poi.ExcelUtil;
import com.gqz.common.core.utils.query.QueryMapperUtil;
import com.gqz.defect.entity.EnStockEquipDefectEntity;
import com.gqz.defect.entity.TEnDefectsSheetEntity;
import com.gqz.defect.entity.TEnDefectsSheetOperateEntity;
import com.gqz.defect.entity.TEnDefectsSheetRelEntity;
import com.gqz.defect.mapper.EnDefectsSheetMapper;
import com.gqz.defect.mapper.EnDefectsSheetOperateMapper;
import com.gqz.defect.mapper.EnDefectsSheetRelMapper;
import com.gqz.defect.mapper.EnStockEquipDefectMapper;
import com.gqz.defect.mapstruct.EnDefectsSheetMapstruct;
import com.gqz.defect.service.IEnDefectsSheetRelService;
import com.gqz.defect.service.IEnDefectsSheetService;
import com.gqz.defect.vo.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * 消缺工单表 业务逻辑实现层ServiceImpl
 */
@Service
@Slf4j
public class EnDefectsSheetServiceImpl extends ServiceImpl<EnDefectsSheetMapper, TEnDefectsSheetEntity> implements IEnDefectsSheetService {

    @Autowired
    private EnDefectsSheetMapstruct mapstruct;
    @Resource
    private IEnDefectsSheetRelService enDefectsSheetRelService;
    @Resource
    private EnStockEquipDefectMapper enStockEquipDefectMapper;
    @Resource
    private EnDefectsSheetRelMapper enDefectsSheetRelMapper;
    @Resource
    private EnDefectsSheetOperateMapper sheetOperateMapper;

    @Override
    public List<EnDefectsSheetVo> getById(String id) {
        MPJLambdaWrapper<TEnDefectsSheetEntity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(TEnDefectsSheetEntity::getId, id);
        queryWrapper.selectAll(TEnDefectsSheetEntity.class);
        List<TEnDefectsSheetEntity> entities = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(entities)) {
            return mapstruct.toVos(entities);
        }
        return new ArrayList<>();
    }

    @Override
    public Page<EnDefectsSheetVo> page(RequestForm<EnDefectsSheetVo> requestForm) {
        MPJLambdaWrapper<TEnDefectsSheetEntity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(TEnDefectsSheetEntity.class);
        queryWrapper.eq(TEnDefectsSheetEntity::getSfsc, 0);
        queryWrapper.orderByDesc(TEnDefectsSheetEntity::getCreateTime);
        if (requestForm.getEntity().getXqdwbm() != null && !"".equals(requestForm.getEntity().getXqdwbm())) {
            queryWrapper.eq(TEnDefectsSheetEntity::getXqdwbm, requestForm.getEntity().getXqdwbm());
        }
        if (requestForm.getEntity().getGdmc() != null && !"".equals(requestForm.getEntity().getGdmc())) {
            queryWrapper.like(TEnDefectsSheetEntity::getGdmc, requestForm.getEntity().getGdmc());
        }
        if (requestForm.getEntity().getGdzt() != null && !"".equals(requestForm.getEntity().getGdzt())) {
            queryWrapper.eq(TEnDefectsSheetEntity::getGdzt, requestForm.getEntity().getGdzt());
        }
        if (requestForm.getEntity().getGdResousId() != null && !"".equals(requestForm.getEntity().getGdResousId())) {
            queryWrapper.eq(TEnDefectsSheetEntity::getGdResousId, requestForm.getEntity().getGdResousId());
        }
        if (requestForm.getEntity().getXqbzbm() != null && !"".equals(requestForm.getEntity().getXqbzbm())) {
            queryWrapper.eq(TEnDefectsSheetEntity::getXqbzbm, requestForm.getEntity().getXqbzbm());
        }
        if (requestForm.getEntity().getJhkssj() != null && !"".equals(requestForm.getEntity().getJhkssj())) {
            queryWrapper.ge(TEnDefectsSheetEntity::getJhkssj, requestForm.getEntity().getJhkssj());
        }
        if (requestForm.getEntity().getJhkssj_to() != null && !"".equals(requestForm.getEntity().getJhkssj_to())) {
            queryWrapper.le(TEnDefectsSheetEntity::getJhkssj, requestForm.getEntity().getJhkssj_to());
        }
        Page<TEnDefectsSheetEntity> page = Page.of(requestForm.getPageNo(), requestForm.getPageSize());
        //page = baseMapper.selectPage(page, queryWrapper);
        IPage<TEnDefectsSheetEntity> iPage = baseMapper.selectJoinPage(page, TEnDefectsSheetEntity.class, queryWrapper);
        page.setRecords(iPage.getRecords());
        page.setTotal(iPage.getTotal());
        return mapstruct.toVos(page);
    }

    @Override
    public Long count(RequestForm<EnDefectsSheetVo> requestForm) {
        TEnDefectsSheetEntity entity = mapstruct.toEntity(requestForm.getEntity());
        MPJLambdaWrapper<TEnDefectsSheetEntity> queryWrapper = QueryMapperUtil.initQueryWrapper(entity, requestForm);
        /** todo getPsrId-> todo-must修改为记录表主键字段todo */
        queryWrapper.select(TEnDefectsSheetEntity::getId);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public int insert(EnDefectsSheetListVo vos) {
        // String sheet_id=this.getDjbh();
        //1.创建工单
        TEnDefectsSheetEntity entitys = new TEnDefectsSheetEntity();
        entitys.setId(vos.getId());
        entitys.setCreatePerson(vos.getCreatePerson());
        entitys.setCreatePersonName(vos.getCreatePersonName());
        entitys.setGdmc(vos.getGdmc());
        entitys.setXqdwbm(vos.getXqdwbm());
        entitys.setXqdwmc(vos.getXqdwmc());
        entitys.setXqbzbm(vos.getXqbzbm());
        entitys.setXqbzmc(vos.getXqbzmc());
        entitys.setJhkssj(vos.getJhkssj());
        entitys.setJhjssj(vos.getJhjssj());
        entitys.setXqnr(vos.getXqnr());
        entitys.setSsjf(vos.getSsjf());
        entitys.setSsjfmc(vos.getSsjfmc());
        Integer num = vos.getDefectsSheetRelVoList().size();
        entitys.setQxyhsl(num.toString());
        entitys.setGdzt("0");
        entitys.setGdztMc("未派单");
        entitys.setGdResousId("0");
        entitys.setGdResousName("平台创建");
        entitys.setCreatePerson(vos.getCreatePerson());
        entitys.setCreatePersonName(vos.getCreatePersonName());
        entitys.setXqzdType(vos.getXqzdType());
        entitys.setXqzdTypeName(vos.getXqzdTypeName());
        int result = 0;
        List<EnDefectsSheetRelVo> entityList = vos.getDefectsSheetRelVoList();
        for (int i = 0, size = entityList.size(); i < size; i++) {
            //2.往关联关系表中插入相关数据
            TEnDefectsSheetRelEntity enDefectsSheetRelEntity = new TEnDefectsSheetRelEntity();
            enDefectsSheetRelEntity.setDefectsId(entityList.get(i).getDefectsId());
            enDefectsSheetRelEntity.setSheetId(vos.getId());
            enDefectsSheetRelMapper.insert(enDefectsSheetRelEntity);
            //3.将缺陷隐患表中的状态改完20-处理中
            EnStockEquipDefectEntity enStockEquipDefectEntity = new EnStockEquipDefectEntity();
            enStockEquipDefectEntity.setId(entityList.get(i).getDefectsId());
            enStockEquipDefectEntity.setDefectStatusCode("20");
            enStockEquipDefectEntity.setDefectStatusName("处理中");
            enStockEquipDefectEntity.setHandleTaskNo(vos.getId());
            enStockEquipDefectEntity.setHandleTaskName(entitys.getGdmc());
            enStockEquipDefectMapper.updateById(enStockEquipDefectEntity);
        }
        result += baseMapper.insert(entitys);
        return result;
    }

    @Override
    public int update(EnDefectsSheetListVo vos) {
        //1.更改工单信息
        TEnDefectsSheetEntity entitys = new TEnDefectsSheetEntity();
        entitys.setId(vos.getId());
        entitys.setCreatePerson(vos.getCreatePerson());
        entitys.setCreatePersonName(vos.getCreatePersonName());
        entitys.setGdmc(vos.getGdmc());
        entitys.setXqdwbm(vos.getXqdwbm());
        entitys.setXqdwmc(vos.getXqdwmc());
        entitys.setXqbzbm(vos.getXqbzbm());
        entitys.setXqbzmc(vos.getXqbzmc());
        entitys.setJhkssj(vos.getJhkssj());
        entitys.setJhjssj(vos.getJhjssj());
        entitys.setXqnr(vos.getXqnr());
        entitys.setSsjf(vos.getSsjf());
        entitys.setSsjfmc(vos.getSsjfmc());
        Integer num = vos.getDefectsSheetRelVoList().size();
        entitys.setQxyhsl(num.toString());
        entitys.setGdzt(vos.getGdzt());
        entitys.setGdztMc(vos.getGdztMc());
        entitys.setGdResousId("0");
        entitys.setGdResousName("平台创建");
        entitys.setCreatePerson(vos.getCreatePerson());
        entitys.setCreatePersonName(vos.getCreatePersonName());
        int result = 0;
        result += baseMapper.updateById(entitys);
        //2.还原之前缺陷隐患信息
        //3.关联关系表数据软删
        List<EnDefectsSheetRelVo> enDefectsSheetRelVos = enDefectsSheetRelService.getBySheetId(vos.getId());
        for (int j = 0; j < enDefectsSheetRelVos.size(); j++) {
            EnStockEquipDefectEntity enStockEquipDefectEntity = new EnStockEquipDefectEntity();
            enStockEquipDefectEntity.setId(enDefectsSheetRelVos.get(j).getDefectsId());
            enStockEquipDefectEntity.setDefectStatusCode("2");
            enStockEquipDefectEntity.setDefectStatusName("审核通过");
            enStockEquipDefectEntity.setHandleTaskNo("");
            enStockEquipDefectEntity.setHandleTaskName("");
            enStockEquipDefectMapper.updateById(enStockEquipDefectEntity);
            TEnDefectsSheetRelEntity enDefectsSheetRelEntity = new TEnDefectsSheetRelEntity();
            enDefectsSheetRelEntity.setId(enDefectsSheetRelVos.get(j).getId());
            enDefectsSheetRelEntity.setSfsc("1");
            enDefectsSheetRelMapper.updateById(enDefectsSheetRelEntity);
        }
        //4.新增关联关系表
        //5.缺陷隐患信息状态改为：20 处理中
        List<EnDefectsSheetRelVo> entityList = vos.getDefectsSheetRelVoList();
        for (int i = 0, size = entityList.size(); i < size; i++) {
            //2.往关联关系表中插入相关数据
            TEnDefectsSheetRelEntity enDefectsSheetRelEntity = new TEnDefectsSheetRelEntity();
            enDefectsSheetRelEntity.setDefectsId(entityList.get(i).getDefectsId());
            enDefectsSheetRelEntity.setSheetId(vos.getId());
            enDefectsSheetRelMapper.insert(enDefectsSheetRelEntity);
            //3.将缺陷隐患表中的状态改完20-处理中
            EnStockEquipDefectEntity enStockEquipDefectEntity = new EnStockEquipDefectEntity();
            enStockEquipDefectEntity.setId(entityList.get(i).getDefectsId());
            enStockEquipDefectEntity.setDefectStatusCode("20");
            enStockEquipDefectEntity.setDefectStatusName("处理中");
            enStockEquipDefectEntity.setHandleTaskNo(vos.getId());
            enStockEquipDefectEntity.setHandleTaskName(entitys.getGdmc());
            enStockEquipDefectMapper.updateById(enStockEquipDefectEntity);
        }
        return result;
    }

    @SneakyThrows
    @Override
    public void exportExcel(HttpServletResponse response, RequestForm<EnDefectsSheetVo> requestForm) {
        //设置信息头，告诉浏览器内容为excel类型
        response.setHeader("content-Type", "application/vnd.ms-excel");
        //文件名称
        String fileName = "消缺工单表信息�?.xls";
        //sheet名称
        String sheetName = "消缺工单表列表";
        fileName = new String(fileName.getBytes(), "ISO-8859-1");
        //设置下载名称
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        if (requestForm.getPageSize() < 1000L) {
            requestForm.setPageSize(1000L);
        }
        //获取到业务数�?
        Page<EnDefectsSheetVo> page = this.page(requestForm);
        new ExcelUtil<>(EnDefectsSheetVo.class).exportExcel(response, page.getRecords(), sheetName);

    }

    @Override
    public Integer deleteByIds(List<String> ids) {
        int result = 0;
        //第一步 原单据软删
        //第二步 缺陷隐患状态还原
        for (int i = 0; i < ids.size(); i++) {
            TEnDefectsSheetEntity enDefectsSheetEntity = new TEnDefectsSheetEntity();
            enDefectsSheetEntity.setId(ids.get(i));
            enDefectsSheetEntity.setSfsc("1");
            List<EnDefectsSheetRelVo> enDefectsSheetRelVos = enDefectsSheetRelService.getBySheetId(ids.get(i));
            for (int j = 0; j < enDefectsSheetRelVos.size(); j++) {
                EnStockEquipDefectEntity enStockEquipDefectEntity = new EnStockEquipDefectEntity();
                enStockEquipDefectEntity.setId(enDefectsSheetRelVos.get(j).getDefectsId());
                enStockEquipDefectEntity.setDefectStatusCode("2");
                enStockEquipDefectEntity.setDefectStatusName("审核通过");
                enStockEquipDefectEntity.setHandleTaskNo("");
                enStockEquipDefectEntity.setHandleTaskName("");
                enStockEquipDefectMapper.updateById(enStockEquipDefectEntity);
            }
            result += baseMapper.updateById(enDefectsSheetEntity);
        }
        return result;
    }

    @Override
    public int pdSend(List<EnDefectsSheetVo> vos) {
        //需要根据id保存派单人、派单时间、派单电话、状态-10 已派单
        List<TEnDefectsSheetEntity> entitys = mapstruct.toEntitys(vos);
        int result = 0;
        for (int i = 0, size = entitys.size(); i < size; i++) {
            TEnDefectsSheetEntity entity = entitys.get(i);
            entity.setGdzt("10");
            entity.setGdztMc("已派单");
            entity.setAppGdzt("1");
            entity.setAppGdztMc("待办");
            result += baseMapper.updateById(entity);
            saveTaskOperate(vos.get(i), "10", "已派单", entitys.get(i).getPdrTime());
        }

        return result;
    }

    @Override
    public int zlpjSend(EnDefectsSheetVo vos) {
        //需要根据id保存审核人、审核时间、审核结论、审核内容、状态-100 归档
        TEnDefectsSheetEntity entitys = mapstruct.toEntity(vos);
        int result = 0;
        if ("100".equals(entitys.getGdzt())) {
            //若审核通过，需要将缺陷隐患信息状态改为已处理
            List<EnDefectsSheetRelVo> enDefectsSheetRelVos = enDefectsSheetRelService.getBySheetId(vos.getId());
            for (int j = 0; j < enDefectsSheetRelVos.size(); j++) {
                EnStockEquipDefectEntity enStockEquipDefectEntity = new EnStockEquipDefectEntity();
                enStockEquipDefectEntity.setId(enDefectsSheetRelVos.get(j).getDefectsId());
                enStockEquipDefectEntity.setDefectStatusCode("100");
                enStockEquipDefectEntity.setDefectStatusName("已处理");
                enStockEquipDefectMapper.updateById(enStockEquipDefectEntity);
            }
            saveTaskOperate(vos, "100", "已归档", entitys.getPjTime());
        } else {
            saveTaskOperate(vos, "20", "已接单", entitys.getPjTime());
            entitys.setAppGdzt("3");
            entitys.setAppGdztMc("退单");
        }

        result += baseMapper.updateById(entitys);
        return result;
    }

    @Override
    public String getDjbh() {
        String timeStr2 = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        Random random = new Random();
        int num = random.nextInt(100);
        return timeStr2 + "" + num;
    }

    @Override
    public List<EnTjVo> getGdStatusXx(String sdate, String edate) {
        MPJLambdaWrapper<TEnDefectsSheetEntity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(TEnDefectsSheetEntity::getSfsc, "0");
        queryWrapper.selectCount(TEnDefectsSheetEntity::getId, "num");
        queryWrapper.selectAs(TEnDefectsSheetEntity::getGdzt, "statusCode");
        queryWrapper.selectAs(TEnDefectsSheetEntity::getGdztMc, "statusName");
        queryWrapper.groupBy(TEnDefectsSheetEntity::getGdzt, TEnDefectsSheetEntity::getGdztMc);
        try {
            Date startDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdate);
            Date endDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(edate);
            if (startDateTime != null && !"".equals(startDateTime)) {
                queryWrapper.ge(TEnDefectsSheetEntity::getJhkssj, startDateTime);
            }
            if (endDateTime != null && !"".equals(endDateTime)) {
                queryWrapper.le(TEnDefectsSheetEntity::getJhkssj, endDateTime);
            }
            List<EnTjVo> entities = baseMapper.selectJoinList(EnTjVo.class, queryWrapper);
            return entities;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 保存任务操作
     *
     * @param taskVo        taskVo
     * @param optStatus     optStatus
     * @param optStatusName optStatusName
     * @param optTime       optTime
     */
    private void saveTaskOperate(EnDefectsSheetVo taskVo, String optStatus, String optStatusName, Date optTime) {
        TEnDefectsSheetOperateEntity operateEntity = new TEnDefectsSheetOperateEntity();
        operateEntity.setTaskNo(taskVo.getId());
        operateEntity.setOptStatus(optStatus);
        operateEntity.setOptStatusName(optStatusName);
        operateEntity.setOptTime(optTime);

        sheetOperateMapper.insert(operateEntity);
    }

    /**
     * 获取流程list
     *
     * @param taskNo
     * @return
     */
    @Override
    public List<TEnDefectsSheetOperateVo> getBaseProcessList(String taskNo) {
        LambdaQueryWrapper<TEnDefectsSheetEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TEnDefectsSheetEntity::getId, taskNo);
        TEnDefectsSheetEntity taskEntity = baseMapper.selectOne(queryWrapper);

        List<TEnDefectsSheetOperateVo> processVos = new ArrayList<>();
        processVos.add(new TEnDefectsSheetOperateVo("工单编制", formatDate(taskEntity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"), 0, 1, "0", "1"));
        processVos.add(new TEnDefectsSheetOperateVo("派单", formatDate(taskEntity.getPdrTime(), "yyyy-MM-dd HH:mm:ss"), 0, 0, "10", "2"));
        processVos.add(new TEnDefectsSheetOperateVo("接单", formatDate(taskEntity.getJdTime(), "yyyy-MM-dd HH:mm:ss"), 0, 0, "20", "3"));
        processVos.add(new TEnDefectsSheetOperateVo("到达现场", formatDate(taskEntity.getDdxcTime(), "yyyy-MM-dd HH:mm:ss"), 0, 0, "30", "4"));
        processVos.add(new TEnDefectsSheetOperateVo("完成消缺", formatDate(taskEntity.getWcxqTime(), "yyyy-MM-dd HH:mm:ss"), 0, 0, "40", "5"));
        processVos.add(new TEnDefectsSheetOperateVo("质量评价", formatDate(taskEntity.getPjTime(), "yyyy-MM-dd HH:mm:ss"), 0, 0, "50", "6"));
        processVos.add(new TEnDefectsSheetOperateVo("归档", formatDate(taskEntity.getPjTime(), "yyyy-MM-dd HH:mm:ss"), 0, 0, "100", "7"));
        for (int i = 0; i < processVos.size(); i++) {
            int gdzt = Integer.parseInt(taskEntity.getGdzt());
            int opStatus = Integer.parseInt(processVos.get(i).getOptStatus());
            if (gdzt > opStatus) {
                processVos.get(i).setIsActive(1);
            } else if (gdzt == opStatus) {
                processVos.get(i).setIsNode(1);
                processVos.get(i).setIsActive(1);
            } else {
                processVos.get(i).setIsActive(0);
                processVos.get(i).setProcessDate("");
            }
        }
        return processVos;
    }

    public String formatDate(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        if (date == null) {
            return "";
        }
        return sdf.format(date);
    }
}
